import BaseContext from '../../context';
import ChapterObserver from './chapterObserver';
import ImageLoader from './imageLoader';
import ReadMode from './readMode';
import ChapterModule from '../../model/chapter';
export default class ComicIndex extends BaseContext {
  constructor(app, options) {
    super(app, options);
    new ImageLoader(app, options);
    new ChapterObserver(app, options);
    new ReadMode(app, options);
    this.api = Object.assign({
      getChapterInfo: `/api/comic/chapter`,
      getAdjoinChapterInfo: `/api/comic/adjoin_chapter`
    }, options.api)
  }

  init() {
    this.listener({
      setChapterInfo: this.setChapterInfo.bind(this),
      loadChapter: this.loadChapter.bind(this)
    });
    this.initRequest();
  }

  setChapterInfo(data) {
    let comicInfo = this.state.comic;
    if (comicInfo) {
      comicInfo.setChapterMap(data);
    } else {
      comicInfo = new ChapterModule(data);
      this.store.set('comic', comicInfo);
      this.emit(['initLoadChapterHtml', 'initLoaded']);
    }
  }

  /**
   * @function requestChapterInfo 章节数据请求
   * @param {Number} comicId 漫画id
   * @param {Number} chapterId 章节id
   * @return promise
   */
  requestChapterInfo(url, params) {
    const { comicId } = this.state.comic || {};
    const { comicId: comic_id = comicId, chapterId: chapter_id } = params;
    return this.request({
      url,
      params: {
        comic_id,
        chapter_id,
        isWebp: this.util.isSupportWebp() ? 1 : 0,
      }
    }).then((res) => {
      if (res.status === 0) {
        this.emit('setChapterInfo', res.data);
      } else {
        this.logger.error(res.message);
      }
      return res;
    }).catch(err => {
      this.logger.error(err);
      return err;
    });
  }
  loadChapter(chapterId) {
    const { currentChapterId } = this.comicInfo;
    if (currentChapterId !== chapterId) {
      this.requestChapterInfo(this.api.getAdjoinChapterInfo, { chapterId })
    }
  }

  initRequest() {
    // 这里通过url获取到当前漫画id和章节id，也可从后端服务把数据吐出到页面上获取
    if (window.comicInfo) {
      this.emit('setChapterInfo', window.comicInfo);
    } else {
      const { comicId, chapterId } = this.options;
      this.requestChapterInfo(this.api.getChapterInfo, { comicId, chapterId });
    }
  }
}
